package xyz.jangle.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class PoiController {
    
    //返回一个ResponseEntity类型
    @RequestMapping("poidownloadtest.html")
    public ResponseEntity<byte[]> poiDownloadTest() throws UnsupportedEncodingException{
        //创建一个excel并写入测试内容
        HSSFWorkbook workbook=new HSSFWorkbook();
        HSSFSheet sheet=workbook.createSheet("downloadTestSheet");
        HSSFRow row=sheet.createRow(0);
        HSSFCell cell=row.createCell(0);
        cell.setCellValue("downTest");
        //创建结束

        	//创建一个字节数组输出流对象
           ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
           try {
        	   //将excel写入输出流
               workbook.write(outputStream);
               workbook.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
        
        HttpHeaders headers=new HttpHeaders();
        String fileName=new String("downloadTest.xls".getBytes("UTF-8"),"iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        
        ResponseEntity<byte[]> returnFile=new ResponseEntity<byte[]>
                            (outputStream.toByteArray(),headers,HttpStatus.CREATED);
        try {
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return returnFile;
    }
}
